package com.demo.service.impl;

import com.demo.service.MessageService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

/**
 * AsyncExecutionInterceptor#invoke方法
 *
 * 		Callable<Object> task = () -> {
 * 			try {
 * 				Object result = invocation.proceed();
 * 				if (result instanceof Future) {
 * 					return ((Future<?>) result).get();
 *              }
 *          }
 * 			catch (ExecutionException ex) {
 * 				handleError(ex.getCause(), userDeclaredMethod, invocation.getArguments());
 * 			}
 * 			catch (Throwable ex) {
 * 				handleError(ex, userDeclaredMethod, invocation.getArguments());
 * 			}
 * 			return null;
 * 		};
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Async
    @Override
    //注意此处的返回值不能使用AsyncResult哦，需要使用Future
    public Future send(String message) {
        System.out.println("发送消息的线程="+Thread.currentThread().getName());
        try {
            System.out.println("消息内容："+message);
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //此处使用的是Spring 对Future的实现类AsyncResult，它的get方法会直接返回构造时传入的值
        //在AsyncExecutionInterceptor#invoke中的task（代码见类头部的注释） 会判断目标方法（即本类的send方法）的返回值是否为Future，是的话会调用get方法将值进行返回
        return new AsyncResult<>("ok");
    }
}
